from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.mail import send_mail, EmailMultiAlternatives
from django.conf import settings
import datetime
import os
import re
import json
import hashlib

from .models import User, ConfirmCode, UserInfo  # 引入数据库 user 对象


def hash_code(s, salt='YMRS'):
    h = hashlib.sha256()
    s += salt
    h.update(s.encode())
    return h.hexdigest()


def send_email(email, code):
    subject = '来自青年租房管理系统的注册确认邮件'

    text_content = '''欢迎注册青年租房管理系统！\
                    如果你看到这条消息，说明你的邮箱服务器不提供HTML链接功能，请联系管理员！'''

    html_content = '''
                    <p>感谢注册<a href="http://43.138.71.90/#/skip?code={}">www.yrms.com</a>，\
                    这里是青年租房管理系统！</p>
                    <p>请点击站点链接完成注册确认！</p>
                    <p>此链接有效期为{}天！</p>
                    '''.format(code, settings.CONFIRM_DAYS)

    msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, [email])
    msg.attach_alternative(html_content, "text/html")
    msg.send()


@csrf_exempt  # 跨域设置
def register(request):  # 继承请求类
    if request.method == 'POST':  # 判断请求方式是否为 POST（要求POST方式）

        data_json = json.loads(request.body)
        username = data_json.get('username', "")
        password_1 = data_json.get('password_1', "")
        password_2 = data_json.get('password_2', "")
        email = data_json.get('email', "")
        mobile = data_json.get('mobile', "")
        if password_1 != password_2:  # 若两次输入的密码不同，则返回错误码errno和描述信息msg
            return JsonResponse({'errno': 1002, 'msg': "两次输入的密码不同"})
        elif re.search(r'[^a-zA-Z0-9]', username):
            return JsonResponse({'errno': 1003, 'msg': "用户名不合法"})
        elif User.objects.filter(username=username).exists():
            return JsonResponse({'errno': 1004, 'msg': "用户名已存在"})
        elif not re.search(r'^[\w]+(\.[\w]+)*@[\w]+(\.[\w])+', email):
            return JsonResponse({'errno': 1005, 'msg': "邮箱地址不合法"})
        elif UserInfo.objects.filter(email=email).exists():
            return JsonResponse({'errno': 1006, 'msg': "该邮箱已被注册"})
        elif len(password_1) < 8 or len(password_1) > 50 \
            or not re.search(r'^[\w]+$', password_1):
            return JsonResponse({'errno': 1007, 'msg': "密码不合法"})
        else:
            # 数据库存取：新建 user 对象，赋值用户名和密码并保存
            new_user = User(username=username, password=password_1)
            new_user.save()  # 一定要save才能保存到数据库中
            new_user_info = UserInfo(id=new_user.id, email=email, mobile=mobile)
            new_user_info.save()
            
            code = hash_code(username, new_user_info.register_time.strftime('%Y-%m-%d %H:%M:%S'))
            ConfirmCode.objects.create(code=code, uid=new_user.id)

            send_email(email, code)
            return JsonResponse({'errno': 0, 'msg': "请前往邮箱验证"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def confirm_user(request):
    if request.method == 'POST':
        data = json.loads(request.body)
    else:
        data = request.GET
    code = data.get('code', "")
    if ConfirmCode.objects.filter(code=code).exists():
        confirmCode = ConfirmCode.objects.get(code=code)
        user = User.objects.get(id=confirmCode.uid)
        user_info = UserInfo.objects.get(id=user.id)
        reg_time = confirmCode.register_time
        now = datetime.datetime.now()

        if now > reg_time + datetime.timedelta(settings.CONFIRM_DAYS):
            confirmCode.delete()
            user.delete()
            user_info.delete()
            return JsonResponse({'errno': 1003, 'msg': "邮件已过期，请重新登录"})
        else:
            confirmCode.delete()
            user_info.confirmed = True
            user_info.save()
            return JsonResponse({'errno': 0, 'msg': "确认成功，请使用该账户登录"})
    else:
        return JsonResponse({'errno': 1002, 'msg': "无效的确认请求"})


@csrf_exempt
def login(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = data_json.get('username', "")
        password = data_json.get('password', "")
        if request.session.get('username', "") != "":
            return JsonResponse({'errno': 1002, 'msg': "用户已登录"})
        elif User.objects.filter(username=username).exists():
            user = User.objects.get(username=username)
            user_info = UserInfo.objects.get(id=user.id)
            if not user_info.confirmed:
                return JsonResponse({'errno': 1005, 'msg': "请前往邮箱确认"})
            elif user.password == password:  # 判断请求的密码是否与数据库存储的密码相同
                request.session['username'] = username  # 密码正确则将用户名存储于session（django用于存储登录信息的数据库位置）
                request.session.set_expiry(0)
                return JsonResponse({'errno': 0, 'msg': "登录成功", 'admin': user.admin, 
                                        'username': request.session.get('username')})
            else:
                return JsonResponse({'errno': 1004, 'msg': "密码错误"})
        else:
            return JsonResponse({'errno': 1003, 'msg': "用户不存在"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def logout(request):
    request.session.flush()
    return JsonResponse({'errno': 0, 'msg': "注销成功"})


@csrf_exempt
def search_users(request):
    if request.method == 'POST':
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        user = User.objects.get(username=username)
        if user.admin:
            res = []
            for user in User.objects.filter(admin=0):
                user_info = UserInfo.objects.get(id=user.id)
                res.append(user_info.get_info())
            return JsonResponse({'errno': 0, 'msg': "查询成功", 'content': res})
        else:
            return JsonResponse({'errno': 1003, 'msg': "非管理员用户"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def lookup_user(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        user = User.objects.get(username=username)
        if user.admin or username == data_json.get('username', ""):
            user_info = UserInfo.objects.get(id=user.id)
            return JsonResponse({'errno': 0, 'msg': "查询成功", 'content': user_info.get_info()})
        else:
            return JsonResponse({'errno': 1003, 'msg': "用户登录信息错误"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def modify_user(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        user = User.objects.get(username=username)
        if user.admin or username == data_json.get('username', ""):
            user_info = UserInfo.objects.get(id=user.id)
            user_info.name = data_json.get('realname', "")
            user_info.sex = data_json.get('sex', 1)
            user_info.mobile = data_json.get('mobile', "")
            user_info.id_number = data_json.get('id_number', "")
            user_info.email = data_json.get('email', "")
            user_info.desc = data_json.get('desc', "")
            
            user_info.save()
            return JsonResponse({'errno': 0, 'msg': "信息修改成功"})
        else:
            return JsonResponse({'errno': 1002, 'msg': "用户登录信息错误"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def add_user(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        user = User.objects.get(username=username)
        if user.admin:
            new_user = User()
            new_user.username = data_json.get('username', "")
            new_user.password = data_json.get('password', "")
            new_user.worker = data_json.get('worker', 1)
            new_user.save()  # 一定要save才能保存到数据库中
            
            new_user_info = UserInfo(id=new_user.id)
            # new_user_info.avatar = request.FILES.get('avatar')
            new_user_info.name = data_json.get('name', "")
            new_user_info.sex = data_json.get('sex', 1)
            new_user_info.mobile = data_json.get('mobile', "")
            new_user_info.id_number = data_json.get('id_number', "")
            new_user_info.email = data_json.get('email', "")
            new_user_info.desc = data_json.get('desc', "")
            new_user_info.save()
            return JsonResponse({'errno': 0, 'msg': "添加成功", 'worker': new_user.id})
        else:
            return JsonResponse({'errno': 1003, 'msg': "非管理员用户"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def getback_pwd(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = data_json.get('username', "")

    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})